package com.sttg.csp.common.dao;

import java.util.HashMap;
import java.util.Map;
import javax.naming.NameNotFoundException;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import com.sttg.csp.common.exception.BizException;
import com.sttg.csp.common.util.LDAPUtil;

public class LoginDAO {

	private static final LoginDAO instance = new LoginDAO();   
	
	/** 
	 * Private the default constructor.
	 */   
	private LoginDAO() {}    
   
	/** 
	 * Static factory methods.
	 */   
	public static LoginDAO getInstance() {
		return instance;    
	}    
	
	/**
	 * Search a BD admin by userid.
	 * @param uid
	 * @return
	 */
	public Map queryBDAdminByUserID(String uid) throws BizException {
		Map<String, String> user = new HashMap<String, String>();
		try {
			SearchControls controls = new SearchControls();
			controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
			Attributes attrs = LDAPUtil.getDirContext().getAttributes("uid=" + uid + "," + LDAPUtil.BD_ADMIN_RDP + "," + LDAPUtil.BASE_DN);
			String userid = LDAPUtil.getAttribute(attrs, "uid");
			String cn = LDAPUtil.getAttribute(attrs, "cn");
			String departmentnumber = LDAPUtil.getAttribute(attrs, "departmentnumber");
			user.put("DP_USER_ID", userid);
			user.put("BD_ADMIN_NAME", cn);
			user.put("DEPARTMENT", departmentnumber);
		}  catch (NameNotFoundException e) {
			// user not found in ldap server.
		} catch (Exception e) {
			throw new BizException(e);
		} finally {
			LDAPUtil.closeConnection();
		}
		return user;
	}
	
	/**
	 * Search a BD user by userid.
	 * @param uid
	 * @return
	 */
	public Map queryBDUserByUserID(String uid) throws BizException {
		Map<String, String> user = new HashMap<String, String>();
		try {
			SearchControls controls = new SearchControls();
			controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
			Attributes attrs = LDAPUtil.getDirContext().getAttributes("uid=" + uid + "," + LDAPUtil.BD_USER_RDP + "," + LDAPUtil.BASE_DN);
			
			String userid = LDAPUtil.getAttribute(attrs, "uid");
			String cn = LDAPUtil.getAttribute(attrs, "cn");
			String departmentnumber = LDAPUtil.getAttribute(attrs, "departmentnumber");
			user.put("BD_USER_ID", userid);
			user.put("BD_USER_NAME", cn);
			user.put("DEPARTMENT", departmentnumber);
		} catch (NameNotFoundException e) {
			// user not found in ldap server.
		} catch (Exception e) {
			throw new BizException(e);
		}finally {
			LDAPUtil.closeConnection();
		}
		return user;
	}
	
}